//
//  RecordModel.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/14.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire

//签入还是签出，0表示签入
enum SignedType: String {
    case signedIn = "0"
    case signedOut = "1"
    case notInRange = "2"   //不在签到范围内
}

class RecordModel: NSObject {
    var itemId: String?     //一条签到记录的id
    var isSupplement: String? //是否补签来的
    var signedTime: Date? //签到时间，系统取下来的是『2017-08-18T09:16:31.843』这样的格式
    var signedType: SignedType? //签入还是签出 0表示签入，1表示签出
    
    required init(JsonData: [String: AnyObject]) {
        self.itemId = JsonData["ID"] as? String
        self.isSupplement = JsonData["IsSupplement"] as? String
        
        if let dateStirng = JsonData["SignedTime"] as? String {
            let date = dateStringWithTToDate(dateString: dateStirng)
            self.signedTime = date
        }
        
        if let signedValue = JsonData["SignedType"] {
            let signedString = "\(signedValue)"
            self.signedType = SignedType(rawValue: signedString)
            
        }
    }
    
}

extension RecordModel {
    
    //签到
    class func record(guid: String,demandBaseMigrantWorkerId: String, signedType: SignedType, completionHandler: @escaping (WWResponse) -> Void) {
        let method = "KouFine.Handler.Core.AjaxOperate.SaveOrderData"
        let pageName = "KouFine.Container.Form"
        let orderConfigId = "B0544B99-B936-2D2E-BC6F-1A54C909145D"
        let orderId = guid
        
        guard let model = WWUser.sharedInstance.userModel else {
            return
        }
        guard let httpHeader = mobile_cilent_headers() else{
            return
        }
        let accountId = model.accountId
        
        //第一层
        let demandBaseMigrantWorker = ["ID":demandBaseMigrantWorkerId]
        
        //第二层
        let isSupplement = "false"
        let form = ["DemandBaseMigrantWorker": demandBaseMigrantWorker,"SignedType":signedType.rawValue,"IsSupplement": isSupplement] as [String : Any]
        
        //第三层
        let jsonData = ["ID":orderId, "Form":form ] as [String : Any]

        let dataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let param = ["Method": method, "pageName": pageName, "orderConfigId":orderConfigId, "orderId":orderId, "jsonData": dataString, "operate":"1", "AccountId": accountId!] as [String : Any]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: param, headers: httpHeader).response { (response) in
            if let data = response.data, let dataString = String(data: data, encoding: .utf8) {
                if dataString == "OK" {
                    completionHandler(WWResponse.init(success: true))
                }
                else {
                    completionHandler(WWResponse.init(success: false, message: dataString))
                }
                
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "签到出错"))
            }
        }
    }
    
    //签到
    class func fastRecord(guid: String,demandBaseMigrantWorkerId: String, signedType: SignedType, completionHandler: @escaping (WWResponse) -> Void) {
        let method = "KouFine.Handler.Core.AjaxOperate.SaveOrderData"
        let pageName = "KouFine.Container.Form"
        let orderConfigId = "B0544B99-B936-2D2E-BC6F-1A54C909145D"
        let orderId = guid
        
        guard let model = WWUser.sharedInstance.userModel else {
            return
        }
        guard let httpHeader = mobile_cilent_headers() else{
            return
        }
        let accountId = model.accountId
        
        //第一层
        let demandBaseMigrantWorker = ["ID":demandBaseMigrantWorkerId]
        
        //第二层
        let isSupplement = "false"
        let form = ["DemandBaseMigrantWorker": demandBaseMigrantWorker,"SignedType":signedType.rawValue,"IsSupplement": isSupplement,"IsAutoSigned":true] as [String : Any]
        
        //第三层
        let jsonData = ["ID":orderId, "Form":form ] as [String : Any]
        
        let dataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let param = ["Method": method, "pageName": pageName, "orderConfigId":orderConfigId, "orderId":orderId, "jsonData": dataString, "operate":"1", "AccountId": accountId!] as [String : Any]
        print(param)
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: param, headers: httpHeader).response { (response) in
            if let data = response.data, let dataString = String(data: data, encoding: .utf8) {
                if dataString == "OK" {
                   completionHandler(WWResponse.init(success: true))
                }
                else {
                    completionHandler(WWResponse.init(success: false, message: dataString))
                }
                
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "签到出错"))
            }
        }
    }
    
    /** 获取签到详情
     signeDate："yyyy-MM-dd"字符串
 */
    class func getRecordData(demandBaseMigrantWorkerID: String, signedDate:String,completionHandler: @escaping (WWValueResponse<[RecordModel]>) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else{
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "KouFine.Handler.Core.AjaxOperate.FindPagingEntityData"
        let domain = "民工管理"
        let typeFullName = "MarTian.MigrantWorkerManage.Entity.DemandBaseMigrantWorkerSigned"
        let orderManagerConfigId = "0081a227-e721-fb84-743a-456c39343723"
        let isQueryControl = "false"
        let sql = "1=1"
        let sqlParam = "{}"
        let pageName = "MarTian.List.MinGongQianDaoJiLuXiangQing"
        let controlName = ""
        let demandBaseMigrantWorkerID = demandBaseMigrantWorkerID
        let signedDate = signedDate
        let start = "0"
        let limit = "25"
        
        let param = ["Method":method, "domain": domain, "typeFullName": typeFullName, "orderManagerConfigId": orderManagerConfigId, "isQueryControl": isQueryControl, "sql": sql, "sqlParam": sqlParam, "pageName": pageName, "controlName": controlName, "DemandBaseMigrantWorkerID":demandBaseMigrantWorkerID, "SignedDate": signedDate, "start": start, "limit": limit, "AccountId": accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: param, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: AnyObject] {
                    
                    var callbackArr = [RecordModel]()
                    if let items = dict["Items"] as? [[String: AnyObject]] {
                        for item in items {
                            let aItem = RecordModel(JsonData: item)
                            callbackArr.append(aItem)
                        }
                        completionHandler(WWValueResponse.init(value: callbackArr, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据有错"))
            }else{
                completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
            }
        }
    }
    //自动签出弹框倒计时结束，会主动调用这个接口。
    class func signOutAutomatically(_ demandBaseMigrantWorkerID: String , completionHandler:@escaping (WWResponse) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else{
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWorkerSigned.AutoSignedOutForApp"
        let params = [
            "Method":method,
            "DemandBaseMigrantWorkerID":demandBaseMigrantWorkerID,
            "AccountId":accountId
        ]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            response.result.ifSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String, status == "OK" {
                        let message = dict["Result"] as? String
                        completionHandler(WWResponse.init(success: true, message: message))
                        return
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "有误"))
            }
            response.result.ifFailure({
               
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            })
        }
    }
    
  }

//某一日的签到合计
class RecordCountInOneDayModel {
    var aId: String?
    var migrantWorkerNo: String?
    var signedInCount: String?  //签入次数
    var signedOutCount: String? //签出次数
    var workingHours: String? //工作时间
    
    required init(jsonDate: [String: AnyObject]) {
        if let aId = jsonDate["ID"] {
            self.aId = aId as? String
        }
        if let migrantWorkerNo = jsonDate["MigrantWorkerNo"] {
            self.migrantWorkerNo = migrantWorkerNo as? String
        }
        if let signedIn = jsonDate["SignedInCount"] {
            self.signedInCount = "\(signedIn)"
        }
        if let signedOut = jsonDate["SignedOutCount"] {
            self.signedOutCount = "\(signedOut)"
        }
        if let hours = jsonDate["WorkingHours"] {
            self.workingHours = "\(hours)"
        }
    }
    
    
    // 当日签到合计
    class func getRecordAcount(marketSupplyBaseId: String, signedDate: String, completionHandler: @escaping (WWValueResponse<[RecordCountInOneDayModel]>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else{
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        //固定参数
        let mehtod = "KouFine.Handler.Core.AjaxOperate.FindPagingEntityData"
        let domain = "民工管理"
        let typeFullName = "MarTian.MigrantWorkerManage.Entity.DemandBaseMigrantWokerSignedRecordView"
        let orderManagerConfigId = "eab96b58-faf6-58a8-6bf6-f6b87d7750ce"
        let isQueryControl = "false"
        let sql = "SignedDate==@SignedDate && MigrantWorker.CompanyMGID == @CompanyMGID"
        let pageName = "MarTian.List.MinGongQianDaoJiLu"
        let controlName = ""
        let start = "0"
        let limit = "25"
        
        //输入参数
        let itemOne = ["Name":"@SignedDate", "Type":"DateTime", "Value":signedDate]
        let itemTwo = ["Name": "@CompanyMGID", "Type": "Guid", "Value": companyId]
        let sqlParam = ["Items": [itemOne, itemTwo]]
        let sqlParamString = getJSONStringFromDictionary(dictionary: sqlParam as NSDictionary)
        
        //组成参数
        let params = ["Method":mehtod, "domain":domain, "typeFullName": typeFullName, "orderManagerConfigId": orderManagerConfigId, "isQueryControl": isQueryControl, "sql":sql, "sqlParam": sqlParamString, "pageName": pageName, "controlName": controlName, "AccountId":accountId, "supplybaseid": marketSupplyBaseId,"start":start, "limit": limit] as [String : Any]
        
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let value = response.result.value {
                    JavascriptJSONjavascript.parse(jsonString: value, completionHandler: { (result, error) in
                        guard error == nil else {
                           
                            completionHandler(WWValueResponse(success: false, message: error!.localizedDescription))
                            return
                        }
                        
                        if let dict = result as? [String: AnyObject] {
                            var dateArray = [RecordCountInOneDayModel]()
                            
                            let items = dict["Items"] as! [[String: AnyObject]]
                            for item in items {
                                let model = RecordCountInOneDayModel(jsonDate: item)
                                dateArray.append(model)
                            }
                            completionHandler(WWValueResponse.init(value: dateArray, success: true))
                        }
                        else {
                            completionHandler(WWValueResponse(success: false, message: "数据格式错误"))
                        }
                    })
                }
            }
            else {
               
                completionHandler(WWValueResponse(success: false, message: "网络错误"))
            }
        }
        
    }
}

//签到策略
class RecordPolicy: NSObject {
    var signedRange: String?  //签到半径
    var longitude: String? // 经度
    var latitude: String? // 纬度
    var electricFenceList:NSArray?
    var signedPointList:NSArray?
    var locationRate: String? // 轨迹上传频率、单位分钟
    
    required init(rootDict: [String: Any]) {
        if let signedRange = rootDict["SignedRange"] {
            self.signedRange = "\(signedRange)"
        }
        if let longitude = rootDict["Longitude"] {
            self.longitude = longitude as? String
        }
        if let latitude = rootDict["Latitude"] {
            self.latitude = latitude as? String
        }
        if let locationRate = rootDict["LocationRate"] {
            self.locationRate = "\(locationRate)"
        }
        if let electricFenceList = rootDict["ElectricFenceList"] as? NSArray{
            self.electricFenceList = electricFenceList
        }
        
        if let signedPointList = rootDict["SignedPointList"] as? NSArray{
            self.signedPointList = signedPointList
        }
        
    }
    
    // 获取签到策略
    class func getRecordPolicy(aID:String, completionHandler: @escaping (WWValueResponse<RecordPolicy>)->Void) {
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWorkerSignedTactics.GetSignedTacticsByID"
        let params = ["Method": method, "MarketSupplyBaseID": aID]
        let headerDic = ["Authorization": "Bearer" + " " + WWUser.sharedInstance.token!]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: headerDic).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String : Any]{
                    
                    let status = dict["Status"] as? String
                    if status == "OK" {
                        if let resultDict = dict["Result"] as? [String: Any] {
                            let model = RecordPolicy(rootDict: resultDict)
                            
                            completionHandler(WWValueResponse.init(value: model, success: true))
                        }
                        else{
                            completionHandler(WWValueResponse(success: false, message: "数据解析错误"))
                        }
                    }
                    else {
                        let result = dict["Result"] as? String
                        completionHandler(WWValueResponse.init(success: false, message: result))
                    }
                    return
                }
                completionHandler(WWValueResponse(success: false, message: "没有获取到数据"))
            }
            else {
                completionHandler(WWValueResponse(success: false, message: "网络访问错误"))
            }
        }
    }

}


/// 补签
class RecordSupply {
    var signedDate: Date?
    var isPayed: Bool = false
    var isOverTimeWork:Bool = false
    
    var exceptionState: ExceptionState = .unSigned
    
    enum ExceptionState: String  {
        case unSigned = "0"
        case signed = "1"
        case other = "2"
        
    }
    
    required init(jsonData: [String: AnyObject]) {
        if let aDate = jsonData["SignedDate"] {
            let dateString = aDate as! String
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss"
            let date = dateFormatter.date(from: dateString)
            self.signedDate = date
        }
        
        if let isPayed = jsonData["IsPayed"] {
            if String(describing: isPayed) == "0" {
                self.isPayed = false
            }
            else {
                self.isPayed = true
            }
        }
        
        if let isOverTimeWork = jsonData["IsOverTimeWork"] {
            if String(describing: isOverTimeWork) == "0" {
                self.isOverTimeWork = false
            }
            else {
                self.isOverTimeWork = true
            }
        }
        
        if let state = jsonData["ExceptionState"] {
            let exceptionState = ExceptionState(rawValue: String(describing: state))
            self.exceptionState = exceptionState ?? .unSigned
        }
    }
    
    //
    /// <#Description#>
    ///
    /// - Parameters:
    ///   - workerId:
    ///   - startTime: 月之首，yyyy-MM-dd HH:mm:ss
    ///   - lastTime: 月之尾,yyyy-MM-dd HH:mm:ss
    ///   - method: 默认的表示按月明细（显示在日历上的）
    class func getRecordStatisticInMonth(workerId: String, startTime: String, lastTime: String,completionHandler: @escaping (WWValueResponse<[RecordSupply]>)-> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }

        let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWokerSignedStatisticsView.GetSignedStatisticsMonthDetailList"
        let workId = workerId
        let params = ["Method": method, "DemandBaseMigrantWorkerID": workId, "StartDate": startTime, "LastDate": lastTime]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                
                var signedArray = [RecordSupply]()
                if let value = response.result.value {
                    for item in value as! [[String: AnyObject]] {
                        
                        let model = RecordSupply(jsonData: item)
                        signedArray.append(model)
                    }
                }
                
                completionHandler(WWValueResponse.init(value: signedArray, success: true))
                
            }
            else {
            completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
            }
        }
        
    }
    
    
    /// 提交补签申请
    ///
    /// - Parameters:
    ///   - guid: guid
    ///   - businessChangerId: 项目业务负责人id，可以在当前项目的model里获取
    ///   - demandBaseMigrantWorkerID: 民工ID，也可以在当前项目的model里获取
    ///   - signedDate: 提交请求的日期,格式yyyy-MM-dd
    ///   - orderNo: 表单接口
    ///   - supplementReason: 补签原因
    class func applyForRecordSupply(guid: String, businessChangerId: String, demandBaseMigrantWorkerID: String, signedDate: String, orderNo: String, supplementReason: String,orderConfigId: String , supplyPoints:String, hourPoints:String,workType:Int,completionHandler: @escaping (WWResponse) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        //固定参数
        let method = "KouFine.Handler.Core.AjaxOperate.SubmitProcess"
        let pageName = "MarTian.Edit.MinGongBuQianXinXi"
        let approvalNote = "提交审批"
        
        //组建参数
        let businessChanger = ["ID":businessChangerId]
        let companyCharger = ["BusinessChanger": businessChanger]
        let company = ["CompanyCharger": companyCharger]
        let demandBaseMigrantWorker = ["ID":demandBaseMigrantWorkerID, "Company": company] as [String : Any]
        let form = ["DemandBaseMigrantWorker":demandBaseMigrantWorker, "SignedDate":signedDate,"SupplementReason":supplementReason,"OrderNo":orderNo,"WorkDays":supplyPoints,"WorkHours":hourPoints,"WorkDayType":workType] as [String : Any]
        
        let jsonData = ["ID":guid, "Form":form, "LiShiBuQian":[], "BuQianMingXi": []] as [String : Any]
        let jsonString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let params = ["pageName":pageName, "orderConfigId":orderConfigId,"orderId":guid, "jsonData":jsonString, "approvalNote":approvalNote, "carbonList":"", "Method": method,"AccountId":accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let value = response.result.value {
                    if value == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        completionHandler(WWResponse.init(success: false, message: value))
                    }
                }
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络请求错误"))
            }
        }

    }
}


enum WorkFlowState: Int {
    case unCommited = 0 //未提交
    case approvalPending = 1 //待审批
    case inTheFlow = 2  //流转中
    case finished = 3   //已完成
    case stop = -1  //被中止
    case returned = -2  //被退回
    case exception = -10 //异常
}
// 申请中的补签记录
class RecordSupplyApply {
    var signedDate: Date?//缺签日期,开工日期
    var createDate: Date? //补签日期,申请时间
    var workFlowState: WorkFlowState?
    var applyId: String? //这个记录的ID
    var demandBaseMigrantWorkerId: String? //选中的项目的demandBaseMigrantWorkerId
    var supplementReason: String? //缺签原因
    
    
    required init(jsonDate: [String: Any]) {
        if let signedDate = jsonDate["SignedDate"] {
            let dateString = signedDate as! String
            let date = dateStringWithTToDate(dateString: dateString)
            self.signedDate = date
        }
        
        if let createDate = jsonDate["CreateTime"] {
            let dateString = createDate as! String
            let date = dateStringWithTToDate(dateString: dateString)
            self.createDate = date
        }
        
        if let workFlowState = jsonDate["WorkflowState"] {
            if let stateInt = workFlowState as? Int {
                let thisState = WorkFlowState(rawValue: stateInt)
                self.workFlowState = thisState
            }
        }
        
        if let applyId = jsonDate["ID"] {
            self.applyId = applyId as? String
        }
        
        if let migrantWorker = jsonDate["DemandBaseMigrantWorker"] as? [String:AnyObject] {
            if let aId = migrantWorker["ID"] {
                self.demandBaseMigrantWorkerId = aId as? String
            }
        }
        
        if let reason = jsonDate["SupplementReason"] {
            self.supplementReason = reason as? String
        }
    }
    
    //获取签到记录
    class func getRecordSupplyApplies( guid: String, marketSupplyBaseID: String, completionHandler: @escaping (WWValueResponse<[RecordSupplyApply]>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId,let companyId = model.companyId  else {
            return
        }
        
        
        let method = "KouFine.Handler.Core.AjaxOperate.FindPagingEntityData"
        let domain = "民工管理"
        let typeFullName = "MarTian.MigrantWorkerManage.Entity.DemandBaseMigrantWorkerSignedSupplement"
        let orderManagerConfigId = "d4446d63-2aa1-59c6-f772-72f641963dea"
        let isQueryControl = "false"
        let sql = "DemandBaseMigrantWorker.MigrantWorker.CompanyMGID==@CompanyMGID"
        let pageName = "MarTian.List.MinGongBuQianQingKuang"
        let controlName = ""
        let start = "0"
        let limit = "25"
        
        let item = ["Name":"@CompanyMGID","Type":"Guid","Value":companyId]
        let sqlParam = ["Items":[item]]
        let sqlParamString = getJSONStringFromDictionary(dictionary: sqlParam as NSDictionary)
        
        let params = ["Method":method, "domain":domain, "typeFullName":typeFullName,"orderManagerConfigId":orderManagerConfigId,"isQueryControl":isQueryControl, "sql":sql, "sqlParam":sqlParamString, "pageName":pageName, "controlName": controlName, "AccountId": accountId, "supplybaseid": marketSupplyBaseID, "start": start, "limit":limit]
        
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                var applyArray = [RecordSupplyApply]()
                
                let valueString = response.result.value!
                JavascriptJSONjavascript.parse(jsonString: valueString, completionHandler: { (result, error) in
                    let dic = result as! [String : Any]
                    if let items = dic["Items"] as? [[String: Any]] {
                        for item in items {
                            let model = RecordSupplyApply(jsonDate: item)
                            applyArray.append(model)
                           
                        }
                        completionHandler(WWValueResponse.init(value: applyArray, success: true))
                        return
                    }
                    completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
                })
                
            }
            else {
               
                completionHandler(WWValueResponse.init(success: false, message: "网络请求错误"))
            }
        }
    }
}

//MARK:补签记录-历史提交记录加载
class RecordCommitHistory {
    var workflowState: WorkFlowState?
    var aId: String?
    var signedData: Date? //签到日期
    var supplementReason: String? //补签原因
    var WorkDays:Float?
    var WorkHours:Float?
    var signedInSupplementDetailList: [SignedSupplementDetail]?   //补签界面的签入时间组
    var signedOutSupplementDetailList: [SignedSupplementDetail]?   //补签界面的签出时间组
    //签入签出时间列表
    struct SignedSupplementDetail {
        var aggregateEntity: String?
        var aggregateEntityID: String?
        var aId: String?
        var operate: Int?
        var signedTime: Date?
        var signedType: SignedType?
        
        init(_ dictData: [String: Any]) {
            self.aggregateEntity = dictData["AggregateEntity"] as? String
            self.aggregateEntityID = dictData["AggregateEntityID"] as? String
            self.aId = dictData["ID"] as? String
            self.operate = dictData["Operate"] as? Int
            if let signedType = dictData["SignedType"]{
                self.signedType = SignedType(rawValue: "\(signedType)")
            }
            if let date = dictData["SignedTime"] as? String {
                self.signedTime = dateStringWithTToDate(dateString: date)
            }
        }
        
    }
    
    
    required init(_ dictData: [String: Any]) {
        if let workflowState = dictData["WorkflowState"] as? Int{
            self.workflowState = WorkFlowState(rawValue: workflowState)
        }
        if let dateStirng = dictData["SignedDate"] as? String {
            let date = dateStringWithTToDate(dateString: dateStirng)
            self.signedData = date
        }
        
        if let arr = dictData["SignedInSupplementDetaiList"] as? [[String: Any]] {
            if arr.count > 0 {
                var details = [SignedSupplementDetail]()
                for dict in arr {
                    let detail = SignedSupplementDetail.init(dict)
                    details.append(detail)
                }
                self.signedInSupplementDetailList = details
            }
        }
        
        if let arr = dictData["SignedOutSupplementDetaiList"] as? [[String: Any]] {
            if arr.count > 0 {
                var details = [SignedSupplementDetail]()
                for dict in arr {
                    let detail = SignedSupplementDetail.init(dict)
                    details.append(detail)
                }
                self.signedOutSupplementDetailList = details
            }
        }
        
        self.aId = dictData["ID"] as? String
        self.supplementReason = dictData["SupplementReason"] as? String
        self.WorkDays = dictData["WorkDays"] as? Float
        self.WorkHours = dictData["WorkHours"] as? Float
    }
    
    
    class func getRecordCommitHistory(_ demandBaseMigrantWorkerId: String, signedDate: String,completionHandler:@escaping (WWValueResponse<RecordCommitHistory>) -> Void) {
        guard let model = WWUser.sharedInstance.userModel,let accountId = model.accountId,let userkey = model.userKey else {
            return
        }

        WWUser.sharedInstance.getToken(accountId, key: userkey) { (isSuccess) in
            if isSuccess {
                guard let httpHeader = mobile_cilent_headers() else {
                    return
                }
                
                let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWorkerSigned.GetSignedSupplementWorkflowRecord"
                let params = ["Method":method, "DemandBaseMigrantWorkerID":demandBaseMigrantWorkerId, "SignedDate":signedDate, "AccountId": accountId]
                Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON(completionHandler: { (response) in
                    if response.result.isSuccess {
                        if let dict = response.result.value as? [String: Any] {
                           
                            if let status = dict["Status"] as? String{
                                if status == "OK" {
                                    let result = dict["Result"] as? [String: Any]
                                    if result != nil {
                                        let model = RecordCommitHistory.init(result!)
                                        completionHandler(WWValueResponse.init(value: model, success: true))
                                        return
                                    }
                                }
                                if status == "Fail" {
                                    let err = dict["Err"] as? String
                                    completionHandler(WWValueResponse.init(success: false, message: err))
                                    
                                    return
                                }
                            }
                        }
                        completionHandler(WWValueResponse.init(success: false, message: "数据出错"))
                    }
                    else {
                        completionHandler(WWValueResponse.init(success: false, message: "网络访问出错"))
                    }
                })
                
            }
            else {
                completionHandler(WWValueResponse.init(success: false, message: "获取token失败，请重新登录"))
            }
        }
    }
}

//补签详情(申请记录点击一个cell进入)
class RecordSupplyDetail {
    var supplementReason: String?
    var signedTime: Date?
    
    required init(jsonData: [String: Any]) {
        if let buqianmingxi = jsonData["BuQianMingXi"] as? [[String: Any]] {
            if buqianmingxi.count > 0 {
                let item = buqianmingxi[0]
                if let dateString = item["SignedTime"] as? String {
                    let signedDate = dateStringWithTToDate(dateString: dateString)
                    self.signedTime = signedDate
                }
            }
        }
        
        if let form = jsonData["Form"] as? [String: Any] {
            if let supplementReason = form["SupplementReason"] {
                self.supplementReason = supplementReason as? String
            }
        }
    }
    
    
    
    /// 获取指定ID的补签详情
    ///
    /// - Parameter orderId: 申请的记录Id
//    class func getRecordSupplyDetailWithId(orderId:String, completionHandler:@escaping (WWValueResponse<RecordSupplyDetail>) -> Void) {
//        let url = JsonAPIURL + "CallMethod"
//        guard let httpHeader = mobile_cilent_headers() else {
//            return
//        }
//        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
//            return
//        }
//        
//        let mehotd = "KouFine.Handler.Core.AjaxOperate.GetEntityOrderByOrderID"
//        let pageName = "MarTian.Edit.MinGongBuQianXinXi"
//        let domain = "民工管理"
//        let typeFullName = "MarTian.MigrantWorkerManage.Entity.DemandBaseMigrantWorkerSignedSupplement"
//        let orderConfigId = "6c2eff7d-fbb8-b727-ae1c-04fcdb47aabe"
//
//        let params = ["Method":mehotd, "pageName":pageName, "domain":domain, "typeFullName":typeFullName, "orderConfigId":orderConfigId, "orderID":orderId, "AccountId": accountId]
//        
//        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
//            if response.result.isSuccess {
//                if let valueString = response.result.value {
//                    JavascriptJSONjavascript.parse(jsonString: valueString, completionHandler: { (result, error) in
//                        let dic = result as! [String : Any]
//                        let model = RecordSupplyDetail(jsonData: dic)
//                        
//                        completionHandler(WWValueResponse.init(value: model, success: true))
//                    })
//                }
//                else {
//                    completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
//                }
//            }
//            else {
//                print("网络请求错误")
//                 completionHandler(WWValueResponse.init(success: false, message: "网络请求错误"))
//            }
//        }
//    }
}

/// 补签详情
class RecordDetail {
    
    required init(_ rootDict: [String: Any]) {
        
    }
    
    ///
    /// 补签详情
    ///
    /// - Parameters:
    ///   - orderId: 对应申请记录的iD
    ///   - completionHandler:
    class func getKeyRecordDetail(_ orderId: String,completionHandler:@escaping (WWValueResponse<[RecordModel]>) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        let method = "KouFine.Handler.Core.AjaxOperate.GetEntityOrderByOrderID"
        let pageName = "MarTian.Edit.MinGongBuQianXinXi"
        let domain = "民工管理"
        let typeFullName = "MarTian.MigrantWorkerManage.Entity.DemandBaseMigrantWorkerSignedSupplement"
        let orderConfigId = "6c2eff7d-fbb8-b727-ae1c-04fcdb47aabe"
        
        let params = ["Method":method, "pageName":pageName, "domain":domain, "typeFullName":typeFullName, "orderConfigId":orderConfigId, "orderID": orderId, "AccountId": accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    
                    if let arr = dict["BuQianMingXi"] as? [[String:AnyObject]] {
                        var callbackArr = [RecordModel]()
                        for item in arr {
                            let model = RecordModel.init(JsonData: item)
                            callbackArr.append(model)
                        }
                        completionHandler(WWValueResponse.init(value: callbackArr, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据解析有误"))
            }
            else {
                completionHandler(WWValueResponse.init(success: false, message: "网络异常"))
            }
        }
        
    }
    
    /// 补签详情签到记录
    ///
    /// - Parameters:
    ///   - demandBaseMigrantWorkerId: 当前项目的DemandBaseMigrantWorkerId
    ///   - signedDate: 签到日期,yyyy-MM-dd
    ///   - signedSupplementId: 进入详情页面的那个cell的ID
    class func getRecordDetail(demandBaseMigrantWorkerId: String, signedDate: String, signedSupplementId: String,completionHandler:@escaping (WWValueResponse<[RecordModel]>)->Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWorkerSigned.GetSignedRecordList"
        let params = ["Method":method, "DemandBaseMigrantWorkerId":demandBaseMigrantWorkerId, "SignedDate": signedDate, "SignedSupplementId": signedSupplementId, "AccountId": accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let valueString = response.result.value {
                    JavascriptJSONjavascript.parse(jsonString: valueString, completionHandler: { (result, error) in
                        var dataArray = [RecordModel]()
                        
                        let arr = result as! [[String : Any]]
                        
                        for item in arr {
                            let model = RecordModel(JsonData: item as [String : AnyObject])
                            dataArray.append(model)
                        }
                        
                completionHandler(WWValueResponse.init(value: dataArray, success: true))
                    })
                }
                else {
                    completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
                }
                
            }
            else {
                completionHandler(WWValueResponse.init(success: false, message: "网络请求错误"))
            }
        }
    }

}

//签到轨迹
class RecordTrack {
    var locateTime: Date?
    var isException: Bool?
    var  aId: String?
    var latitude: String? //维度
    var longitude: String? //经度
    
    
    
    required init(jsonDict: [String: Any]) {
        if let locateTime = jsonDict["LocateTime"] as? String {
            self.locateTime = dateStringWithTToDate(dateString: locateTime)
        }
        if let isException = jsonDict["isException"]  {
            let aString = "\(isException)"
            if aString == "1" {
                self.isException = true
            }
            else {
                self.isException = false
            }
        }
        
        self.latitude = jsonDict["Latitude"] as? String
        self.longitude = jsonDict["Longitude"] as? String
        self.aId = jsonDict["ID"] as? String
    }
    
    //获取轨迹
    class func getRecordTrack(marketSupplyBaseID: String,start: Int = 0, startOfDay:String, endOfDay: String, completionHandler:@escaping (WWValueResponse<[RecordTrack]>) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId ,let companyId = model.companyId else {
            return
        }
        
        let method = "KouFine.Handler.Core.AjaxOperate.FindPagingEntityData"
        let domain = "民工管理"
        let typeFullName = "MarTian.MigrantWorkerManage.Entity.DemandBaseMigrantWorkerLocation"
        let orderManagerConfigId = "e088edeb-d053-10eb-b144-e0b1eb0f5cb9"
        let isQueryControl = "false"
        let sql = "LocateTime>=@LocateTime_Start&&LocateTime<=@LocateTime_End&&DemandBaseMigrantWorker.MigrantWorker.CompanyMGID == @CompanyMGID"
        let pageName = "MarTian.List.GuiJiYiChangXinXi"
        let controlName = ""
        let start = "\(start)"
        let limit = "25"
        
        //组合Json
        let firstItem = ["Name": "@LocateTime_Start", "Type": "DateTime", "Value": startOfDay]
        let secondItem = ["Name": "@LocateTime_End", "Type": "DateTime", "Value": endOfDay]
        let thirdItem = ["Name": "@CompanyMGID", "Type": "Guid", "Value": companyId]
        let sqlParam = ["Items":[firstItem,secondItem,thirdItem]]
        let sqlparamString = getJSONStringFromDictionary(dictionary: sqlParam as NSDictionary)
        
        let params = ["Method":method, "domain":domain, "typeFullName": typeFullName, "orderManagerConfigId": orderManagerConfigId, "isQueryControl": isQueryControl, "sql": sql, "sqlParam":sqlparamString, "pageName":pageName, "controlName": controlName, "supplybaseid": marketSupplyBaseID, "start": start, "limit":limit, "AccountId": accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
               
                if let dict = response.result.value as? [String: Any] {
                    
                    if let items = dict["Items"] as? [[String: Any]] {
                        var callbackArr = [RecordTrack]()
                        
                        for item in items {
                            let model = RecordTrack(jsonDict: item)
                            callbackArr.append(model)
                        }
                        completionHandler(WWValueResponse.init(value: callbackArr, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据获取异常"))
            }
            else {
               
                completionHandler(WWValueResponse.init(success: false, message: "网络请求错误"))
            }
        }
    }
    
    //上传轨迹
    class func uploadRecordTrack(_ guid: String, demandBaseMigrantWorkerID: String, isException: Bool, longitude: String, latitude: String ,userAdress:String, completionHandler:@escaping (WWResponse) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        let method = "KouFine.Handler.Core.AjaxOperate.SaveOrderData"
        let pageName = "KouFine.Container.Form"
       // let orderConfigId = "a4f52b11-694d-4094-af5a-c69a11ed6b5d"
        let orderConfigId = "2BA1B75D-88F0-0856-15A9-6A4C0A13933B"
        let operate = "1"
        let demandBaseMigrantWorker = ["ID":demandBaseMigrantWorkerID]
        let form = ["DemandBaseMigrantWorker":demandBaseMigrantWorker, "IsException":"\(isException)", "Longitude":longitude, "Latitude":latitude,"Address":userAdress] as [String : Any]
        let jsonData = ["ID": guid, "Form":form] as [String : Any]
        let jsonDataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
    
        let params = ["Method":method, "pageName":pageName, "orderConfigId": orderConfigId, "orderId": guid, "jsonData": jsonDataString, "operate": operate, "AccountId":accountId] as [String : Any]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            
            if response.result.isSuccess {
                if let str = response.result.value {
                    if str == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        completionHandler(WWResponse.init(success: false, message: str))
                    }
                }
            }
            else {
                
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
}
